package com.szxy.config;

import com.szxy.domain.ActiverUser;
import com.szxy.domain.User;
import com.szxy.service.MenuService;
import com.szxy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;


/**
 * @Author: zwz
 * @Date:2020/7/20 23:50
 * @Description:com.szxy.config
 * @Version:1.0 自定义 Realm 匹配用户名和密码
 **/
public class UserRealm extends AuthorizingRealm {

    //延时加载注入，第一次使用 userRealm 对象才会注入 userService 对象
    @Autowired
    @Lazy
    private UserService userService;
    @Autowired
    @Lazy
    private MenuService menuService;

    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户登录手机号
        String phone = token.getPrincipal().toString();
        // 根据手机号查询用户主体信息
        User user = this.userService.queryUserByPhone(phone);
        if (null != user) {
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            // TODO: 2020/7/21  查询用户的角色和权限信息

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    activerUser
                    , user.getPassword()
                    , ByteSource.Util.bytes(user.getSalt())
                    , this.getName()
            );
            return info;
        }
        return null;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiverUser activerUser = (ActiverUser) principals.getPrimaryPrincipal();
        // TODO: 2020/7/21 获取用户角色和权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

}
